﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using HengTong.Model.Db;
using HengTong.Model.Db.Other;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Wtm.Models;
using UUIDNext;


namespace HengTong.ViewModel.Activity.SysActivityParticipationVms
{
    public partial class SysActivityParticipationVm : BaseCRUDVM<SysActivityParticipation>
    {
        public List<SysActivitImages> SelectedActivityImagesIds { get; set; }

        public SysActivityParticipationVm()
        {
            SetInclude(x => x.Activity);
            SetInclude(x => x.User);
        }

        protected override void InitVM()
        {
            if (Entity.HasID())
            {
                SelectedActivityImagesIds = DC.Set<SysActivitImages>()
                    .Where(e => e.ActivityParticipationId == Entity.ID)
                    .ToList();
            }
        }

        public override async Task DoAddAsync()
        {
            var activity = await DC.Set<SysActivityList>()
                .AsNoTracking()
                .FirstOrDefaultAsync(e => e.ID == Entity.ActivityId);

            if (activity == null || activity.ActivityStatus != ActivityStatus.进行中)
            {
                MSD.AddModelError("", "当前活动不是进行中，无法报名！");
                return;
            }
            
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
                Entity.UserId = Guid.Parse(Wtm.LoginUserInfo!.UserId);
            }
            
            //检查当前用户是否超过允许参加次数
            var participationCount = await DC.Set<SysActivityParticipation>()
                .CountAsync(x => x.UserId == Entity.UserId && x.ActivityId == Entity.ActivityId);
            if (participationCount >= activity.MaxJoinCount)
            {
                //提示该活动最多参加次数是多少，已经参加多少提示了
                MSD.AddModelError("", $"您已报名参加该活动 {participationCount} 次，本活动最多可参加 {activity.MaxJoinCount} 次，无法再次参与！");
                return;
            }
            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            await base.DoAddAsync();
            //把图片添加到活动参与的图片组中
            if (SelectedActivityImagesIds.Any())
            {
                
                foreach (var item in SelectedActivityImagesIds)
                {
                    item.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
                    item.ActivityParticipationId = Entity.ID;
                    item.Order = item.Order;
                }

                await DC.Set<SysActivitImages>().AddRangeAsync(SelectedActivityImagesIds);

                await DC.SaveChangesAsync();
            }
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            //把图片添加到活动参与的图片组中
            if (SelectedActivityImagesIds.Any())
            {
                //先删除原有的图片组
                var existingImages = DC.Set<SysActivitImages>()
                    .Where(x => x.ActivityParticipationId == Entity.ID).ToList();
                if (existingImages.Any())
                {
                    DC.Set<SysActivitImages>().RemoveRange(existingImages);
                }
                
                foreach (var item in SelectedActivityImagesIds)
                {
                    item.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
                    item.ActivityParticipationId = Entity.ID;
                    item.Order = item.Order;
                }

                await DC.Set<SysActivitImages>().AddRangeAsync(SelectedActivityImagesIds);

                await DC.SaveChangesAsync();
            }

            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoEditAsync(updateAllFields);
        }

        public async Task ApproveAsync(bool upAllFields = false)
        {
            DC = Wtm.CreateDC();
            var transaction = DC.BeginTransaction();
            try
            {
                if (Entity is IFlow flow)
                {
                    flow.Approver = Wtm.LoginUserInfo?.ITCode;
                    flow.ApprovalTime = DateTime.Now;
                }

                await base.DoEditAsync(upAllFields);
                if (MSD.IsValid)
                {
                    await ContinueWorkflowAsync(ActionName, Remark);
                    await transaction.CommitAsync();
                }
                else
                {
                    await transaction.RollbackAsync();
                }
            }
            catch (Exception e)
            {
                // 回滚事务
                await transaction.RollbackAsync();
                MSD.AddModelError(" ", $"审批操作异常: {e.Message}");
            }
            finally
            {
                await transaction.DisposeAsync();
            }
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }
    }
}